import request from '../../../api/request'
const USERINFO = {
  namespaced: true,
  state: {
    token: '',
    id: '',
    headUrl: '',
    name: '',
    loginStatus: false, // 是否登录 true是 false否
    tokenStatus: false // token是否过期  false 否
  },
  mutations: {
    saveToken (state, token) {
      state.token = token
    },
    saveUserInfo (state, data) {
      state.id = data.id
      state.headUrl = data.headimgurl
      state.name = data.name
      state.loginStatus = true
    },
    initUserInfo (state) {
      state.token = ''
      state.id = ''
      state.headUrl = ''
      state.name = ''
      state.loginStatus = false
    },
    updataTokenStatus (state, status) {
      state.tokenStatus = status
    }
  },
  actions: {
    login (context, data) {
      return new Promise((resolve, reject) => {
        request.post('login', data).then((response) => {
          if (response.data.code === '200') {
            context.commit('saveToken', response.data.data.token)
            localStorage.setItem('token', response.data.data.token)
            context.commit('saveUserInfo', response.data.data)
            context.commit('updataTokenStatus', false)
          } else if (response.data.code === '401') { // token过期
            context.commit('updataTokenStatus', true)
          }
          resolve(response.data)
        })
      })
    },
    getUserInfo (context) {
      return new Promise((resolve, reject) => {
        request.post('userInfo').then((response) => {
          resolve(response.data)
        })
      })
    }
  }
}
export default USERINFO
